#include "txFIFO.h"

can_message_t canTxBuffer[CAN_TXBUFFER_SIZE];
TxFIFOCtrl_t TxFIFOCtrl = {
    .totalSize = CAN_TXBUFFER_SIZE,
    .totalRepeat = 1,
    .pBuffer = canTxBuffer
};

uint8_t pushTxFIFO(TxFIFOCtrl_t *ctrl, can_message_t msg)
{
    uint8_t ret = 0;
    if(ctrl->usedSize <= ctrl->totalSize) {
        uint8_t index = (ctrl->index + ctrl->usedSize) % ctrl->totalSize;
        memcpy(&ctrl->pBuffer[index], &msg, sizeof(can_message_t));
        ctrl->usedSize++;
    } else {
        ret = 1;
    }

    return ret;
}

void txFIFOTask(TxFIFOCtrl_t *ctrl)
{
    if(ctrl->usedSize > 0) {
        if(ctrl->usedRepeat != ctrl->totalRepeat) {
        	// user handle begin
            // if(CAN0_TxBufferIsBusy(0)) return ;
        	// can_send(ctrl->pBuffer[ctrl->index].id, ctrl->pBuffer[ctrl->index].data, ctrl->pBuffer[ctrl->index].dlc);
            // user handle end
            ctrl->usedRepeat++;
            if(ctrl->usedRepeat >= ctrl->totalRepeat) {
                ctrl->usedRepeat = 0;
                ctrl->index++;
                ctrl->usedSize--;
                if(ctrl->index >= ctrl->totalSize) ctrl->index = 0;
            }
        }
    }
}

